from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.remote.webelement import WebElement
from typing import Union


class ElementAction:
    '''元素操作
    '''

    def __init__(self, driver: WebDriver):
        self.driver = driver

    # 选择单个元素 *feature(元组)：解包
    def _find_el(self, feature: Union[tuple, WebElement]):
        if isinstance(feature, tuple):
            return self.driver.find_element(*feature)
        elif isinstance(feature, WebElement):
            return feature

    # 选择多个元素
    def _find_els(self, feature: tuple):
        return self.driver.find_elements(*feature)

    # 点击
    def _click(self, feature: Union[tuple, WebElement]):
        return self._find_el(feature).click()

    # 输入
    def _input(self, feature: Union[tuple, WebElement], content: str):
        return self._find_el(feature).send_keys(content)

    # 清空输入框
    def _clear(self, feature: Union[tuple, WebElement]):
        return self._find_el(feature).clear()

    # 清空并输入
    def _clear_and_input(self, feature: Union[tuple, WebElement], content: str):
        self._clear(feature)
        return self._input(feature, content)

    # 获取元素的指定属性
    def _get_attribute(self, feature: Union[tuple, WebElement], attribute='outerText') -> str:
        return self._find_el(feature).get_attribute(attribute)

    # 显示等待
    def _wait_element(self, feature: Union[tuple, WebElement], timeout=5) -> Union[WebElement, None]:
        try:
            el: WebElement = WebDriverWait(self.driver, timeout).until(expected_conditions.presence_of_element_located(feature))
            return el
        except Exception:
            return None

    # 判断元素是否存在 返回bool
    def _is_element_exist(self, feature: Union[tuple, WebElement], timeout=1):
        try:
            return self._wait_element(feature, timeout)
        except Exception:
            return None
